package com.cel.Service;

import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.baidu.aip.imageclassify.AipImageClassify;
import com.baidu.aip.ocr.AipOcr;
import com.thoughtworks.xstream.XStream;

import cmo.cel.entity.AccessToken;
import cmo.cel.entity.Article;
import cmo.cel.entity.BaseMessage;
import cmo.cel.entity.ImageMessage;
import cmo.cel.entity.MusicMessage;
import cmo.cel.entity.NewsMessage;
import cmo.cel.entity.TextMessage;
import cmo.cel.entity.VideoMessage;
import cmo.cel.entity.VoiceMessage;
import cmo.cel.util.Util;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

//87bdfe817ed53a76
public class WxService {
	private static final String TOKEN = "Frank";
	private static final String GET_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	private static final String APPID = "wxd97e986874f21500";
	private static final String APPSECRET = "85db21d1011a1d33054bcee66b777563";
//	public static final String http = "http://66au8s.natappfree.cc/WeCHat";
	private static final Object MsgId = null;
	private static final Object PicUrl = null;
	private static AccessToken at;
	private static String mediaId;
	private static String format;
	private static String recognition;
	private static String msgId;

	public static final String APP_ID = "17881810";
	public static final String API_KEY = "bjOhgTfoLhIeKRoaNG9FFX7p";
	public static final String SECRET_KEY = "Du1m9W0Ya2E0mpIKhgGNnvyh6ezdF9G2";
	private static final String APPKEY = "1fec136dbd19f44743803f89bd55ca62";

	// 文字识别
//	public static final String APP_ID = "17879118";
//	public static final String API_KEY = "GPp63KtrIcY423SS17jLnyr4";
//	public static final String SECRET_KEY = "QawVHhHGOkeit2FmAKNnpFB0IQwl6P7s";

	// 获取token
	private static void getToekn() {
		String url = GET_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
		String tokenStr = Util.get(url);
		JSONObject jsonObject = JSONObject.fromObject(tokenStr);
		String token = jsonObject.getString("access_token");
		String expireIn = jsonObject.getString("expires_in");
		// 创建token对象,并存起来
		at = new AccessToken(token, expireIn);
//		System.out.println(tokenStr);
	}

//开放的获取token的方法
	public static String getAccessToken() {
		if (at == null || at.isExpired()) {
			getToekn();
		}
		return at.getAccessToken();

	}

	// 验证签名
	public static boolean check(String timestamp, String nonce, String signature) {
		// 参数字典排序
		String[] strs = new String[] { TOKEN, timestamp, nonce };
		Arrays.sort(strs);
		// 拼接并sha1加密
		String str = strs[0] + strs[1] + strs[2];
		String mysig = sha1(str);
//		System.out.println(mysig);
//		System.out.println(signature);
		// 加密后的字符串与signature对比
		return mysig.equalsIgnoreCase(signature);
	}

	// 进行加密
	private static String sha1(String src) {
		try {
			// 获取加密对象
			MessageDigest md = MessageDigest.getInstance("sha1");
			// 加密
			byte[] digest = md.digest(src.getBytes());
			char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
			StringBuilder sb = new StringBuilder();
			// 处理加密结果
			for (byte b : digest) {
				sb.append(chars[(b >> 4) & 15]);
				sb.append(chars[b & 15]);
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 解析xml数据包
	public static Map<String, String> parseRequest(InputStream is) {
		Map<String, String> map = new HashMap<String, String>();
		SAXReader reader = new SAXReader();
		try {
			// 读取输入流,获取文档对象
			Document document = reader.read(is);
			// 获取根节点
			Element root = document.getRootElement();
			// 获取子节点
			List<Element> elements = root.elements();
			for (Element e : elements) {
				map.put(e.getName(), e.getStringValue());
				System.out.println(e.getName() + " : " + e.getStringValue());
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return map;
	}

	// 用于处理所有的事件及消息回复
	// 返回的是xml格式数据包
	public static String getRespose(Map<String, String> requestMap) {
		BaseMessage msg = null;
		String msgType = requestMap.get("MsgType");
		switch (msgType) {
		case "text":
			msg = dealTextMessage(requestMap);
			break;
		case "image":
			msg = dealImage(requestMap);
			break;
		case "voice":
			msg = dealVoice(requestMap);
			break;
		case "video":

			break;
		case "shortvideo":

			break;
		case "location":

			break;
		case "link":

			break;
		case "event":
			msg = dealEvent(requestMap);
			break;
		default:
			break;
		}
		// 把消息对象处理为xml数据包
		if (msg != null) {
			return beanToxml(msg);
		}
		return null;
	}

	private static BaseMessage dealVoice(Map<String, String> requestMap) {
		VoiceMessage voice = new VoiceMessage(requestMap, requestMap.get(mediaId), requestMap.get(format), recognition,
				msgId, format);
		String msg = requestMap.get("Voice");

		return new VoiceMessage(requestMap, mediaId, recognition, recognition, msg, msg);
	}

	// 图片文字识别
	private static BaseMessage dealImage(Map<String, String> requestMap) {

		
		AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY); // 可选：设置网络连接参数
		client.setConnectionTimeoutInMillis(2000);
		client.setSocketTimeoutInMillis(60000); // 调用接口
		String path = requestMap.get("PicUrl");
		org.json.JSONObject res = client.basicGeneralUrl(path, new HashMap<String, String>());
		String json = res.toString();
		JSONObject jsonObject = JSONObject.fromObject(json);
		JSONArray jsonArray = jsonObject.getJSONArray("words_result");
		Iterator<JSONObject> it = jsonArray.iterator();
		StringBuilder sb = new StringBuilder();
		while (it.hasNext()) {
			JSONObject next = it.next();
			sb.append(next.getString("words"));
		}
		return new TextMessage(requestMap, sb.toString());

		
		  
//		  String mediaId = requestMap.get("MediaId");
//		  return new ImageMessage(requestMap, requestMap.get("PicUrl"), mediaId, requestMap.get("MsgId"));
//		  if (mediaId != null) { 
////			  return new ImageMessage(requestMap, mediaId);
//			  return new ImageMessage(requestMap,requestMap.get("PicUrl"), mediaId, requestMap.get(MsgId));
//			  ImageMessage im =  new ImageMessage(requestMap, requestMap.get("PicUrl"), mediaId,requestMap.get("MsgId")); 
//			  List<Article> articles = new ArrayList<>();
//			  articles.add(new Article("这是标题",
//					  					"这是描述", 
//					  					requestMap.get("PicUrl"),
//					  					"http://9ca7rp.natappfree.cc/WeCHat"));
//		  
//		  AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY); // 可选：设置网络连接参数
//		  client.setConnectionTimeoutInMillis(2000);
//		  client.setSocketTimeoutInMillis(60000); 
//		  // 调用接口 
//		  String path =  requestMap.get("PicUrl");
//		  org.json.JSONObject res = client.basicGeneral(path, new HashMap<String, String>());
//		  String json = res.toString(); 
//		  JSONObject jsonObject = JSONObject.fromObject(json); 
//		  JSONArray jsonArray = jsonObject.getJSONArray("words_result");
//		  Iterator <JSONObject> it = jsonArray.iterator();
//		  StringBuilder sb = new StringBuilder();
//		  while(it.hasNext()) { 
//			  JSONObject next = it.next();
//			  sb.append(next.getString("words"));
//		  
//		  }
//		  
//		   NewsMessage nm = new NewsMessage(requestMap, articles); 
//		   return new TextMessage(requestMap, sb.toString()); 
//		   return nm;

	}

	// 处理事件推送
	private static BaseMessage dealEvent(Map<String, String> requestMap) {
		String event = requestMap.get("Event");
		switch (event) {
		case "CLICK":
			return dealClick(requestMap);
		case "VIEW":
			return dealView(requestMap);
		default:
			break;
		}
		return null;
	}

	private static BaseMessage dealView(Map<String, String> requestMap) {

		return null;
	}

	private static BaseMessage dealClick(Map<String, String> requestMap) {
		String key = requestMap.get("EventKey");
		switch (key) {
		case "1":
			return new TextMessage(requestMap, "https://music.163.com");
		case "32":
			return new TextMessage(requestMap, "让你点你就点啊😂");
		default:
			break;
		}
		return null;
	}

	// 把消息对象处理为xml数据包
	private static String beanToxml(BaseMessage msg) {
		XStream stream = new XStream();
		stream.processAnnotations(TextMessage.class);
		stream.processAnnotations(ImageMessage.class);
		stream.processAnnotations(MusicMessage.class);
		stream.processAnnotations(NewsMessage.class);
		stream.processAnnotations(VideoMessage.class);
		stream.processAnnotations(VoiceMessage.class);
		String xml = stream.toXML(msg);
		return xml;
	}

	// 处理文本消息
	private static BaseMessage dealTextMessage(Map<String, String> requestMap) {
//		TextMessage tm = new TextMessage(requestMap, requestMap.get("Content"));
		// 用户发来的消息
		String msg = requestMap.get("Content");
		if (msg.equals("图文")) {
			List<Article> articles = new ArrayList<>();
			articles.add(new Article("这是标题", "这是描述",
					"http://mmbiz.qpic.cn/mmbiz_jpg/Yx9kJIyicQG9kTpA8erqIiaL8IEGYpc4pibibemp5989UYuGwZdBf1qOTUrDZgOQ6ibzFxW9dpcBHVNiaPK3V1vLwnyw/0",
					"http://vb29u9.natappfree.cc/WeCHat"));
			NewsMessage nm = new NewsMessage(requestMap, articles);
			return nm;
		} else if (msg.equals("你叫什么") || msg.equals("你叫什么名字") || msg.equals("你叫什么名字呀")|| msg.equals("你是")) {
			return new TextMessage(requestMap, "你的小宝贝啦！");
		}
		// 调用方法返回聊天内容
		String resp = chat(msg);
		TextMessage tm = new TextMessage(requestMap, resp);
		return tm;
	}

	private static String chat(String msg) {
		String request = null;
		// 接口地址
		String url = "http://op.juhe.cn//robot/index";
		// 请求参数
		Map<String, String> params = new HashMap<String, String>();
//		接口APPKEY
		params.put("key", APPKEY);
//		发送的内容<30字节
		params.put("info", msg);
		// 返回的数据格式,默认json
		params.put("dtype", "");
//		Map params = new HashMap();
////		接口APPKEY
//		params.put("key", APPKEY);
////		发送的内容<30字节
//		params.put("info", msg);
//		// 返回的数据格式,默认json
//		params.put("dtype", "");

//		params.put("loc", "");
//		params.put("lon", "");
//		params.put("lat", "");
//		params.put("userid", "");
		try {
			request = Util.net(url, params, "GET");
			JSONObject jsonObject = JSONObject.fromObject(request);
			int code = jsonObject.getInt("error_code");
			if (code != 0) {
				return null;
			}
			String resp = jsonObject.getJSONObject("result").getString("text");
			return resp;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}